package com.mybatis.firstMybatis;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import com.yiibai.mybatis.models.User;
import com.yiibai.mybatis.models.UserMapper;

public class App2 {
	public static void main(String[] args) throws SQLException {
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://127.0.0.1:3306/yiibai?useSSL=false";
		String username = "root";
		String password = "123456";
		// 创建使用缓存池的数据源
		/*
		 * <dataSource type="POOLED"> <property name="driver"
		 * value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/>
		 * <property name="username" value="${jdbc.username}"/> <property
		 * name="password" value="${jdbc.password}"/> </dataSource>
		 */
		DataSource dataSource = new PooledDataSource(driver, url, username, password);

		// 创建事务
		/*
		 * <transactionManager type="JDBC" />
		 */
		TransactionFactory transactionFactory = new JdbcTransactionFactory();

		Environment environment = new Environment("development", transactionFactory, dataSource);

		Configuration configuration = new Configuration(environment);
		// 加入资源
		/*
		 * <mapper resource="ssm/BlogMapper.xml"/>
		 */
		configuration.addMapper(UserMapper.class);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
		System.out.println(sqlSessionFactory);

		SqlSession session = sqlSessionFactory.openSession();
		try {
			//User user1 = (User) session.selectOne("com.yiibai.mybatis.models.UserMapper.GetUserByID", 1);
			
			UserMapper mapper = session.getMapper(UserMapper.class);
			User user = mapper.selectUser(1);

			if (user != null) {
				String userInfo = "名字：" + user.getName() + ", 所属部门：" + user.getDept() + ", 主页：" + user.getWebsite();
				System.out.println(userInfo);
			}
		} finally {
			session.close();
		}
	}

}
